"use strict";

var mysql = require('mysql');
var request = require('request');
var util = require('util');
var EventEmitter = require('events').EventEmitter;


// all event
// connected: connect to db succ
// count,size: get the count(*) size
// sqlResult,list : get the query result
// saveToEsDone, body : save success
function SyncMysqlData() {

}
util.inherits(SyncMysqlData, EventEmitter);
var sp = SyncMysqlData.prototype;

/**
 *
 * @param maxCount
 * @param fromCount
 */
sp.init = function (maxCount, fromCount, pageSize) {
    console.log('init');
    this.maxCount = maxCount;
    this.fromCount = fromCount ? fromCount : 0;
    this.pageSize = pageSize ? pageSize : 500;
    this.stepInfo = {};
};

sp.start = function () {
    console.log('start');
    var connection = mysql.createConnection({
        host: '192.168.61.10',
        port: 3306,
        user: 'root',
        database: 'mahoo_test',
        password: '3h98dfjs'
    });
    var self = this;
    this.connection = connection;
    connection.connect(function (err) {
        if (err) throw err;
        self.emit('connected')
    });
};

sp.getCount = function () {
    //console.log('getCount');
    var self = this;
    var sql = 'select count(*) from mh_post_content ';
    self.connection.query(sql, function (err, rows, fields) {
        var count = rows[0]["count(*)"];
        self.count = count;
        self.emit('count', count);
    });
};

sp.nextPageIndex = function () {
    //console.log('nextPageIndex');
    if (!this.pageIndex) {
        this.pageIndex = 1;
    }
    var t = this.pageIndex;
    this.pageIndex++;
    return t;
};

var fs = require('fs');
var path = require('path');
var file = path.join(__dirname, 'syn.log');
sp.logStep = function () {

    var msg = '-----------------\n';
    for (var key in this.stepInfo) {
        msg += (key + ':' + this.stepInfo[key] + '\n');
    }
    this.stepInfo = {};
    fs.appendFile(file, msg, function (err, res) {
        if (err) console.log(err);
    });
};

/**
 {
     "uid":"xxx",
     "articleId":"xxx",
     "nickName":"xxx",
     "articleContent":"xxx"
 }
 * @returns {*}
 */
sp.getSelectSql = function () {
    //console.log('getSelectSql');
    var self = this;
    var offset = (this.nextPageIndex() - 1) * this.pageSize + this.fromCount;
    self.stepInfo.offset = offset;
    self.stepInfo.limit = this.pageSize;
    if (this.maxCount > 0 && offset - this.fromCount >= this.maxCount) {
        console.log('reach maxCount');
        return null;
    }
    if (offset > this.count) {
        console.log('reach all');
        return null;
    }
    var sql =
        " select t1.pid, t1.uid, t1.post, t2.nickname from mh_post_content as t1," +
        " mh_user as t2" +
        " where t1.uid=t2.uid" +
        " limit " + this.pageSize + ' offset ' + offset;
    return sql;
};

/**
 {
     "uid":"xxx",
     "articleId":"xxx",
     "nickName":"xxx",
     "articleContent":"xxx"
 }
 * @returns {*}
 */
sp.queryForResult = function () {
    //console.log('queryForResult');
    var self = this;
    var sql = self.getSelectSql();
    if (!sql) {
        self.emit('done');
        return;
    }
    console.log(sql);
    self.connection.query(sql, function (err, rows, fields) {
        if (err) throw err;
        var list = [];
        // TODO 过滤,对某些无意义的进行过滤
        self.stepInfo.getCount = rows.length;
        rows.forEach(function (item) {
            //if (item.post.length > 0) list.push(item.post);
            var obj = {
                uid: item.uid,
                articleId: item.pid,
                nickName: item.nickname,
                articleContent: item.post
            };
            list.push(obj);
            //if (item.post.length > 0) {
            //}
        });
        self.emit('sqlResult', list);
    });
};

var url = 'http://localhost:1888/api/v2/article/batch';
sp.saveToEs = function (list) {
    //console.log('saveToEs');
    var self = this;
    request({
        method: 'POST',
        url: url,
        json: true,
        headers: {"content-type": "application/json"},
        body: list
    }, function (err, response, body) {
        if (err) {
            throw err;
        }
        //console.log('save to es success');
        //console.log(body);
        self.stepInfo.save = 'success';
        self.emit('saveToEsDone', body);
    });
};


sp.stop = function () {
    console.log('stop');
    this.connection.end();
    this.emit('stop');
};

var syn = new SyncMysqlData();
syn.init(-1, 0, 2000); // (maxCount, fromCount, pageSize)
// connected: connect to db succ
// count,size: get the count(*) size
// sqlResult,list : get the query result
// saveToEsDone, body : save success
// done : all done
// stop : connection over
syn.on('connected', function () {
    this.getCount();
});
syn.on('count', function (count) {
    console.log('count=' + count);
    this.queryForResult();
});
syn.on('sqlResult', function (list) {
    this.saveToEs(list);
});
syn.on('saveToEsDone', function () {
    var self = this;
    self.logStep();
    process.nextTick(function () {
        self.queryForResult();
    });
});
syn.on('done', function () {
    this.stop();
});
syn.start();


